package com.scpii.universal.pns.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;

import javax.annotation.Resource;

import net.sf.json.JSONObject;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import com.scpii.universal.constant.GenericConstants;
import com.scpii.universal.hibernate.dao.CatelogDao;
import com.scpii.universal.hibernate.dao.ContentDao;
import com.scpii.universal.hibernate.entity.CatelogTab;
import com.scpii.universal.hibernate.entity.ContentTab;
import com.scpii.universal.pns.dao.ActivitiesDao;
import com.scpii.universal.pns.dao.AppConfigsDao;
import com.scpii.universal.pns.dao.ClientUserDtoDao;
import com.scpii.universal.pns.dao.CommentsDao;
import com.scpii.universal.pns.dao.DevicesDao;
import com.scpii.universal.pns.dao.EcOrdersDao;
import com.scpii.universal.pns.dao.EcProductDao;
import com.scpii.universal.pns.dao.FieldDao;
import com.scpii.universal.pns.dao.UserActionPointConfigDao;
import com.scpii.universal.pns.dao.UserActionStateDao;
import com.scpii.universal.pns.dao.UserActionsDao;
import com.scpii.universal.pns.dao.UserDevicesDao;
import com.scpii.universal.pns.dao.UserLinksDao;
import com.scpii.universal.pns.dao.UserPointRanksDao;
import com.scpii.universal.pns.dao.UsersDao;
import com.scpii.universal.pns.dto.ClientUserDto;
import com.scpii.universal.pns.dto.FieldImageDto;
import com.scpii.universal.pns.dto.UserConfigDto;
import com.scpii.universal.pns.dto.UserDetailDto;
import com.scpii.universal.pns.dto.UserRegFieldDto;
import com.scpii.universal.pns.entity.AppConfigs;
import com.scpii.universal.pns.entity.Comments;
import com.scpii.universal.pns.entity.Devices;
import com.scpii.universal.pns.entity.EcProduct;
import com.scpii.universal.pns.entity.Field;
import com.scpii.universal.pns.entity.UserActionPointConfig;
import com.scpii.universal.pns.entity.UserActionState;
import com.scpii.universal.pns.entity.UserActions;
import com.scpii.universal.pns.entity.UserDevices;
import com.scpii.universal.pns.entity.UserLinks;
import com.scpii.universal.pns.entity.UserPointRanks;
import com.scpii.universal.pns.entity.Users;

@Service
public class ClientUsermanageServiceImpl extends
		PnsBaseServiceImpl<ClientUserDto, Long> implements
		ClientUserManageService {

	@Resource
	private ClientUserDtoDao clientUserDtoDao;

	@Resource
	private UserLinksDao userLinksDao;

	@Resource
	private UserActionStateDao userActionStateDao;

	@Resource
	private DevicesDao devicesDao;

	@Resource
	private UsersDao usersDao;

	@Resource
	private CommentsDao commentsDao;

	@Resource
	private ActivitiesDao activitiesDao;

	@Resource
	private UserDevicesDao userDevicesDao;

	@Resource
	private ResourcesService resourcesService;

	@Resource
	private UserActionsService userActionsService;

	@Resource
	private UserActionsDao userActionsDao;

	@Resource
	private ContentDao contentDao;

	@Resource
	private UserPointRanksDao userPointRanksDao;

	@Resource
	private AppConfigsDao appConfigsDao;

	@Resource
	private FieldDao fieldDao;

	@Resource
	private EcProductDao ecProductDao;

	@Resource
	private EcOrdersDao ecOrdersDao;

	@Resource
	private CatelogDao catelogDao;

	// ---------积分规则配置start----
	@Resource
	private UserActionPointConfigDao userActionPointConfigDao;

	// ---------积分规则配置end-----

	private static final String ALL_NOT_ALLOW_KEY = "NO";
	private static final String ALLOW_KEY = "REGISTER_ALLOW_KEY";
	private static final String ALLOW_AREA = "REGISTER_ALLOW_AREA";

	@Resource
	public void setBaseDao(ClientUserDtoDao clientUserDtoDao) {
		super.setBaseDao(clientUserDtoDao);
	}

	@Override
	public List<Map<String, Object>> getClientUserInit(Integer appId,
			ClientUserDto condition, Integer pageNo, Integer pageSize) {
		return usersDao.getClientUserInit(GenericConstants.APP_ID_PRE + appId,
				condition, pageNo, pageSize);
	}

	@Override
	public Integer getClientUserInitCount(Integer appId, ClientUserDto condition) {
		return usersDao.getClientUserInitCount(GenericConstants.APP_ID_PRE
				+ appId, condition);

	}

	/**
	 * 查询用户的社交账号
	 * 
	 * @param userDto
	 */
	public void getUserLinks(ClientUserDto userDto) {
		StringBuffer hql = new StringBuffer(
				"select  t from UserLinks t where t.userId=:userId");
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("userId", userDto.getUserId());

		List<UserLinks> list = userLinksDao.findByHql(hql.toString(), 0, 0,
				map, null);
		userDto.setUlks(list);
	}

	/**
	 * 查询用户统计
	 * 
	 * @param userDto
	 */
	private void getUserActionsCount(ClientUserDto userDto) {
		StringBuffer hql = new StringBuffer(
				"select t from UserActionState t where t.userId=:userId");
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("userId", userDto.getUserId());

		List<UserActionState> list = userActionStateDao.findByHql(
				hql.toString(), 0, 0, map, null);
		if (list != null && list.size() > 0) {
			for (UserActionState uks : list) {
				if (GenericConstants.USER_ACTIONS_COMMENTS_ADD.equals(uks
						.getActionType())) {
					userDto.setCommentCount(uks.getCount());
				} else if (GenericConstants.USER_ACTIONS_ACTIVITES_FAV
						.equals(uks.getActionType())) {
					userDto.setFavCount(uks.getCount());
				} else if (GenericConstants.USER_ACTIONS_REPLAY_ADD.equals(uks
						.getActionType())) {
					userDto.setReplayCount(uks.getCount());
				} else if (GenericConstants.USER_ACTIONS_ACTIVITES_JOIN
						.equals(uks.getActionType())) {
					userDto.setActiviJoinCount(uks.getCount());
				} else if (GenericConstants.USER_ACTIONS_EC_FAVORITE.equals(uks
						.getActionType())) {
					userDto.setFavCount(userDto.getFavCount() + uks.getCount());
				} else if (GenericConstants.USER_ACTIONS_EC_ORDER_ADD
						.equals(uks.getActionType())) {
					userDto.setEcOrderCount(uks.getCount());
				}
			}
		}

		// 查询用户订单数
		hql = new StringBuffer(
				"select count(*) from EcOrders t where t.userId=:userId");
		map = new HashMap<String, Object>();
		map.put("userId", userDto.getUserId());
		List<Long> ordrs = ecOrdersDao.findByHqlCount(hql.toString(), 0, 0,
				map, null);
		if (ordrs != null) {
			userDto.setEcProductCount(ordrs.get(0).intValue());
		}

	}

	@Override
	public List<Devices> getDeviceInfoByAppId(Integer appId) {

		StringBuffer hql = new StringBuffer(
				"select t from Devices t where t.appId=:appId");
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("appId", GenericConstants.APP_ID_PRE + appId);
		List<Devices> list = devicesDao.findByHql(hql.toString(), 0, 0, map,
				null);
		List<Devices> devList = new ArrayList<Devices>();
		Map<String, String> devMap = new HashMap<String, String>();
		if (list != null && list.size() > 0) {
			for (Devices dev : list) {
				if (dev.getDeviceModel() != null
						&& !"".equals(dev.getDeviceModel())) {
					if (!devMap.containsKey(dev.getDeviceModel())) {
						devList.add(dev);
						devMap.put(dev.getDeviceModel(), dev.getDeviceModel());
					}
				}
			}
		}
		return devList;
	}

	@Override
	public ClientUserDto getUserDetailInfo(Long userId) {
		StringBuffer hql = new StringBuffer(
				"select new com.scpii.universal.pns.dto.ClientUserDto(u.id as userId,");
		hql.append("u.userName,");
		hql.append("u.createDt,");
		hql.append("u.userType,");
		hql.append("u.userAilas,");
		hql.append("u.avatar,");
		hql.append("u.lastActivityDt,u.rankId, u.rankPoint ,u.provider)");
		hql.append(" from Users u");
		hql.append(" where u.id=:userId");
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("userId", userId);
		// 查询用户信息
		List<ClientUserDto> list = clientUserDtoDao.findByHql(hql.toString(),
				0, 0, map, null);
		if (list != null && list.size() > 0) {
			for (ClientUserDto userDto : list) {
				// 查询用户的社交账号
				getUserLinks(userDto);
				// 查询用户的操作统计
				getUserActionsCount(userDto);

				Devices dev = getUserDevviceByUserId(userDto.getUserId());
				if (dev != null) {
					userDto.setDeviceModel(new String[] { dev.getDeviceModel() });
				}
				String imgPath = ResourceBundle.getBundle(
						GenericConstants.GLOBAL_PROPERTIES_PATH,
						Locale.getDefault()).getString("pns.img.path");
				if (userDto.getAvatar() != null
						&& !userDto.getAvatar().startsWith("http://")) {
					userDto.setAvatar(imgPath + userDto.getAvatar());
				}
				if (userDto.getRankId() == null) {
					userDto.setRankId((short) 0);
				}
			}

		}
		return list.get(0);
	}

	@Override
	public List<UserDetailDto> getUserActionsByUserId(Long userId,
			Integer pageNo, Integer pageSize) {
		List<UserActions> usList = userActionsService.getUserActionsByUserId(
				userId, pageNo, pageSize);
		List<UserDetailDto> udList = new ArrayList<UserDetailDto>();
		if (usList != null && usList.size() > 0) {

			UserDetailDto udDto = null;
			for (UserActions action : usList) {
				udDto = new UserDetailDto();
				udDto.setEventTime(action.getCreateDt());
				udDto.setActionType(action.getActionType());
				if (GenericConstants.USER_ACTIONS_COMMENTS_ADD.equals(action
						.getActionType())) {
					Comments comm = commentsDao.get(action.getObjectId());
					if (comm != null) {
						udDto.setComments(comm);
						udDto.setResources(resourcesService.getPhotoInfo(
								comm.getId(), 0, 0));
						getEventContent(comm.getTargetId(), udDto, comm);
					}
				} else if (GenericConstants.USER_ACTIONS_USER_LOGIN
						.equals(action.getActionType())) {
					udDto.setStatusMsg("登陆成功");
					getEventContent(action.getUserId(), udDto, null);
				} else if (GenericConstants.USER_ACTIONS_COMMENTS_LIKE
						.equals(action.getActionType())) {
					udDto.setStatusMsg("赞了一下");
					getEventContent(action.getTargetId(), udDto, null);
				} else if (GenericConstants.USER_ACTIONS_ACTIVITES_JOIN
						.equals(action.getActionType())) {
					udDto.setStatusMsg("参加了活动");
					getEventContent(action.getTargetId(), udDto, null);
				} else if (GenericConstants.USER_ACTIONS_ACTIVITES_FAV
						.equals(action.getActionType())) {
					udDto.setStatusMsg(null);
					getEventContent(action.getTargetId(), udDto, null);
				} else if (GenericConstants.USER_ACTIONS_REPLAY_ADD
						.equals(action.getActionType())) {
					Comments comm = commentsDao.get(action.getObjectId());
					if (comm != null) {
						Comments commReplay = commentsDao.get(comm
								.getParentId());
						Long createBy = commReplay.getCreateBy();
						Users users = usersDao.get(createBy);
						udDto.setReplayUserName(users != null ? users
								.getUserAilas() : null);
						udDto.setStatusMsg(comm.getContent());
						getEventContent(commReplay.getTargetId(), udDto, comm);
					}
				} else if (GenericConstants.USER_ACTIONS_EC_FAVORITE
						.equals(action.getActionType())) {
					udDto.setStatusMsg("电商收藏");
					getEventContent(action.getTargetId(), udDto, null);
				} else if (GenericConstants.USER_ACTIONS_EC_ORDER_ADD
						.equals(action.getActionType())) {
					udDto.setStatusMsg("添加预订");
					getEventContent(action.getTargetId(), udDto, null);
				}
				udList.add(udDto);
			}
		}
		return udList;
	}

	@Override
	public Integer getUserActionsByUserIdCount(Long userId) {
		StringBuffer hql = new StringBuffer(
				" select count(*) from UserActions u "
						+ "where u.userId=:userId");
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("userId", userId);
		List<Long> list = userActionsDao.findByHqlCount(hql.toString(), 0, 0,
				map, null);
		if (list != null && list.size() == 1) {
			return list.get(0).intValue();
		} else {
			return 0;
		}

	}

	/**
	 * 查询action时间的发生点
	 * 
	 * @param action
	 * @return
	 */
	private void getEventContent(Long targetId, UserDetailDto uDto,
			Comments comm) {
		String eventContent = "";
		String eventFrom = "";
		if (targetId.toString().startsWith(
				GenericConstants.USER_ACTIONS_APP_PRE_ACTIVITIES)) {
			eventContent = activitiesDao.get(targetId).getTitle();
			eventFrom = "活动";
		} else if (targetId.toString().startsWith(
				GenericConstants.USER_ACTIONS_APP_PRE_USERS)) {
			Devices dev = getUserDevviceByUserId(targetId);
			if (dev != null) {
				eventContent = dev.getDeviceName();
			} else {
				eventContent = "";
			}
		} else if (targetId.toString().startsWith(
				GenericConstants.USER_ACTIONS_APP_PRE_CIRCLE)) {
			eventFrom = "圈子";
			if (comm.getParentId() == 0) {
				eventContent = comm.getContent();
			} else {

				eventContent = getCommentsByChildId(comm.getId());
			}
		} else if (targetId.toString().startsWith(
				GenericConstants.USER_ACTIONS_APP_PRE_COMMENTS)) {
			Comments commRe = commentsDao.get(targetId);
			eventContent = commRe.getContent();
			eventFrom = "评论";
		} else if (targetId.toString().startsWith("37")) {
			EcProduct pro = ecProductDao.get(targetId);
			eventContent = pro.getTitle();
			eventFrom = "电商";
		} else if (targetId.toString().startsWith("48")) {
			ContentTab tab = contentDao.get(getActivitesIdByTargetId(targetId));
			if (tab != null) {
				eventContent = tab.getVarContentName();
			}
			CatelogTab cateLog = catelogDao.get(tab.getIntCateId());
			eventFrom = cateLog.getVarCateName();
			if (uDto.getStatusMsg() == null) {
				if (cateLog.getIntType() == 0) {
					uDto.setStatusMsg("预订了" + tab.getVarContentName());
				} else {
					uDto.setStatusMsg("收藏 了" + eventFrom);
				}
			}
		}

		uDto.setEventFrom(eventFrom);
		uDto.setEventConent(eventContent);

	}

	/**
	 * 根据用户查找设备
	 * 
	 * @param userId
	 * @return
	 */
	private Devices getUserDevviceByUserId(Long userId) {
		StringBuffer hql = new StringBuffer(
				"select t from UserDevices t where t.userId=:userId and  t.status=1");
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("userId", userId);
		List<UserDevices> list = userDevicesDao.findByHql(hql.toString(), 0, 0,
				map, null);
		if (list != null && list.size() > 0) {
			Devices device = devicesDao.get(list.get(0).getDeviceId());
			return device;
		} else {

			return null;
		}
	}

	/**
	 * 根据品论表的ID查找顶级父类的内容
	 * 
	 * @param id
	 * @return
	 */
	private String getCommentsByChildId(Long id) {
		String str = "";
		StringBuffer sql = new StringBuffer();
		sql.append("select {comm.*} from pns.COMMENTS comm");
		sql.append(" start with comm.ID=:resId");
		sql.append(" connect by prior comm.PARENT_ID=comm.ID order by comm.id ASC");

		Map<String, Object> argsMap = new HashMap<String, Object>();
		argsMap.put("resId", id);
		List<Comments> list = commentsDao.findBySql(sql.toString(), argsMap);
		if (list != null && list.size() > 0) {
			for (Comments comm : list) {
				if (comm.getParentId() == 0) {
					str = comm.getContent();
					break;
				}
			}
		}
		return str;
	}

	private Integer getActivitesIdByTargetId(Long targetId) {
		String str = targetId.toString().replace("48", "");
		while (str.startsWith("0")) {
			str = str.substring(1);
		}
		return Integer.parseInt(str);
	}

	/**
	 * 用户等级初始化查询
	 */
	@Override
	public List<UserPointRanks> getUserLevelInit(Integer appId, Integer pageNo,
			Integer pageSize) {
		StringBuffer hql = new StringBuffer("select t from UserPointRanks t");
		hql.append(" where t.appid=:appid order by maxPoints asc");
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("appid", GenericConstants.APP_ID_PRE + appId);
		// 查询用户信息
		List<UserPointRanks> list = userPointRanksDao.findByHql(hql.toString(),
				pageNo, pageSize, map, null);
		return list;
	}

	@Override
	public Integer getUserLevelInitCount(Integer appId) {
		StringBuffer hql = new StringBuffer(
				"select count(*) from UserPointRanks t");
		hql.append(" where t.appid=:appid");
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("appid", GenericConstants.APP_ID_PRE + appId);
		List<Long> list = userPointRanksDao.findByHqlCount(hql.toString(), 0,
				0, map, null);
		if (list != null && list.size() == 1) {
			return list.get(0).intValue();
		} else {
			return 0;
		}
	}

	@Override
	public void saveUserLevel(UserPointRanks userPointRanks) {
		UserPointRanks persistRanks = userPointRanksDao.getByAppIdAndMaxPoints(
				userPointRanks.getAppid(), userPointRanks.getMaxPoints());
		if (persistRanks != null) {
			persistRanks.setRankImg(userPointRanks.getRankImg());
			persistRanks.setUpdateDt(new Date());
			persistRanks.setRankName(userPointRanks.getRankName());
			userPointRanksDao.update(persistRanks);
		} else {
			userPointRanksDao.save(userPointRanks);
		}
	}

	@Override
	public UserPointRanks getUserLevel(Long id) {
		return userPointRanksDao.get(id);
	}

	@Override
	public void updateUserLevel(UserPointRanks userPointRanks) {
		UserPointRanks temp = userPointRanksDao.get(userPointRanks.getId());
		if (userPointRanks.getRankImg() != null
				&& !userPointRanks.getRankImg().equals("")) {
			temp.setRankImg(userPointRanks.getRankImg());
		}
		temp.setRankName(userPointRanks.getRankName());
		temp.setMaxPoints(userPointRanks.getMaxPoints());
		temp.setMinPoints(userPointRanks.getMinPoints());
		temp.setUpdateBy(userPointRanks.getUpdateBy());
		temp.setUpdateDt(new Date());
		userPointRanksDao.update(temp);

	}

	@Override
	public void removeUserLevel(Long id) {
		userPointRanksDao.delete(id);

	}

	@Override
	public UserConfigDto saveUserConfigInit(Integer appId, Long userId) {
		UserConfigDto userConfigDto = new UserConfigDto();
		Map<String, String> configs = appConfigsDao.getByKeys(
				GenericConstants.APP_ID_PRE + appId, new String[] { ALLOW_KEY,
						ALLOW_AREA });
		String[] str = { "T_SINA", "T_TENCENT", "PHONE" };
		if (configs != null) {
			String allowKey = configs.get(ALLOW_KEY);
			String allowArea = configs.get(ALLOW_AREA);
			if (allowKey == null || "".endsWith(allowKey)) {
				userConfigDto.setAllowReg(1);
				userConfigDto.setAllowType(str);
			} else if (ALL_NOT_ALLOW_KEY.equals(allowKey)) {
				userConfigDto.setAllowReg(0);
			} else {
				userConfigDto.setAllowReg(1);
				userConfigDto.setAllowType(StringUtils.split(allowKey, ","));
				userConfigDto.setAllowRule(allowArea);
			}
		} else {
			userConfigDto.setAllowReg(1);
			userConfigDto.setAllowType(str);
		}

		// 获取注册字段的值
		StringBuffer hql = new StringBuffer(
				"select t from com.scpii.universal.pns.entity.Field t");
		hql.append(" where t.appId=:appid");
		hql.append(" and t.categoriesId=:categoriesId");
		hql.append(" and status>=:status");
		hql.append(" order by id asc ");
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("appid", GenericConstants.APP_ID_PRE + appId);
		map.put("categoriesId", 16L);
		map.put("status", (short) 2);
		// 查询用户信息
		List<Field> fieldList = fieldDao.findByHql(hql.toString(), 0, 0, map,
				null);
		for (Field field : fieldList) {
			if (field.getMask() != null && !field.getMask().equals("")) {
				field.setUserRegFieldDto(getListByJson(field.getMask()));
			}
		}
		userConfigDto.setFieldList(fieldList);
		return userConfigDto;
	}

	private UserRegFieldDto getListByJson(String json) {
		JSONObject object = JSONObject.fromObject(json);
		UserRegFieldDto dto = new UserRegFieldDto();
		if (object != null) {

			String ja = object.getString("optionValues");
			dto.setOptionValues(ja);
			String required = object.getString("required");
			if ("true".equals(required) || required == null) {
				dto.setRequired("是");
			} else {
				dto.setRequired("否");
			}
			dto.setOptionImageUrls(object.getString("optionImageUrls"));
		}

		return dto;
	}

	@Override
	public void saveUserConfig(UserConfigDto userConfigDto, Integer appId,
			Long userId, List<FieldImageDto> imageList) {
		Field field = new Field();
		field.setAliasName(StringUtils.trim(userConfigDto.getFieldName()));
		field.setName(StringUtils.trim(userConfigDto.getFieldName()));
		field.setMetaType(userConfigDto.getFieldType());
		field.setCategoriesId(16L);
		if ("true".equals(userConfigDto.getReqiured())) {
			field.setStatus((short) 3);
		} else {
			field.setStatus((short) 2);
		}
		StringBuffer sb = new StringBuffer("{");
		sb.append("\"required\":" + userConfigDto.getReqiured() + "");
		// 普通值
		if (imageList != null) {
			StringBuffer fieldValues = new StringBuffer("");
			StringBuffer imageValues = new StringBuffer("");
			fieldValues.append(",\"optionValues\":[");
			imageValues.append(",\"optionImageUrls\":[");
			int size = imageList.size();
			int i = 0;
			for (FieldImageDto imageDto : imageList) {
				if (imageDto != null) {
					if (i == size - 1) {
						fieldValues.append("\"" + imageDto.getValue() + "\"");
						if (imageDto.getFilePath() != null
								&& !"".equals(imageDto.getFilePath())) {
							imageValues.append("\"" + imageDto.getFilePath()
									+ "\"");
						}
					} else {
						fieldValues.append("\"" + imageDto.getValue() + "\",");
						if (imageDto.getFilePath() != null
								&& !"".equals(imageDto.getFilePath())) {
							imageValues.append("\"" + imageDto.getFilePath()
									+ "\",");
						}
					}
				}
				i++;

			}
			fieldValues.append("]");
			imageValues.append("]");
			sb.append(fieldValues);
			sb.append(imageValues);
		}

		sb.append("}");
		field.setMask(sb.toString());
		field.setAppId(GenericConstants.APP_ID_PRE + appId);
		field.setCreateBy(userId);
		field.setCreateDt(new Date());
		Field persitField = fieldDao.selectByField(field);
		if (persitField != null) {
			persitField.setAliasName(field.getAliasName());
			persitField.setUpdateDt(new Date());
			persitField.setMask(field.getMask());
			persitField.setMetaType(field.getMetaType());
			persitField.setStatus(field.getStatus());
			fieldDao.update(persitField);
		} else {
			fieldDao.save(field);
		}
	}

	@Override
	public void updateUserConfigPre(UserConfigDto userConfigDto, Integer appId) {
		if (userConfigDto == null) {
			return;
		}

		if (userConfigDto.getAllowType() != null) {
			AppConfigs allowKeyConfig = appConfigsDao.getByKey(
					GenericConstants.APP_ID_PRE + appId, ALLOW_KEY);
			if (allowKeyConfig != null) {
				allowKeyConfig
						.setValue(userConfigDto.getAllowReg() == 0 ? ALL_NOT_ALLOW_KEY
								: StringUtils.join(
										userConfigDto.getAllowType(), ","));
				allowKeyConfig.setType(1);
				appConfigsDao.update(allowKeyConfig);
			} else {
				allowKeyConfig = new AppConfigs();
				allowKeyConfig.setAppId(GenericConstants.APP_ID_PRE + appId);
				allowKeyConfig.setCreateDt(new Date());
				allowKeyConfig.setKey(ALLOW_KEY);
				allowKeyConfig
						.setValue(userConfigDto.getAllowReg() == 0 ? ALL_NOT_ALLOW_KEY
								: StringUtils.join(
										userConfigDto.getAllowType(), ","));
				allowKeyConfig.setTitle("允许注册");
				allowKeyConfig.setType(1);
				appConfigsDao.save(allowKeyConfig);
			}
		}
		if (userConfigDto.getAllowRule() != null) {
			AppConfigs allowAreaConfig = appConfigsDao.getByKey(
					GenericConstants.APP_ID_PRE + appId, ALLOW_AREA);
			if (!ArrayUtils.contains(userConfigDto.getAllowType(), "PHONE")
					|| StringUtils.isBlank(userConfigDto.getAllowRule())) {
				if (allowAreaConfig != null) {
					appConfigsDao.delete(allowAreaConfig);
				}
				return;
			}
			if (allowAreaConfig != null) {
				allowAreaConfig.setType(1);
				allowAreaConfig.setValue(userConfigDto.getAllowRule());
				appConfigsDao.update(allowAreaConfig);
			} else {
				allowAreaConfig = new AppConfigs();
				allowAreaConfig.setType(1);
				allowAreaConfig.setAppId(GenericConstants.APP_ID_PRE + appId);
				allowAreaConfig.setCreateDt(new Date());
				allowAreaConfig.setKey(ALLOW_AREA);
				allowAreaConfig.setValue(userConfigDto.getAllowRule());
				allowAreaConfig.setTitle("允许注册");
				appConfigsDao.save(allowAreaConfig);
			}
		}
	}

	@Override
	public void removeUserField(Long id) {
		fieldDao.delete(id);
	}

	@Override
	public List<Field> getUserFields(Integer appId, Long userId) {

		StringBuffer hql = new StringBuffer(
				"select new  com.scpii.universal.pns.entity.Field(t.aliasName ,t1.valueStr as fieldValue)");
		hql.append(" from Field t,FieldValues t1");
		hql.append(" where  t.id=t1.fieldId  and t.appId=:appid");
		hql.append(" and t1.targetId=:targetId");
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("appid", GenericConstants.APP_ID_PRE + appId);
		map.put("targetId", userId);
		List<Field> list = fieldDao.findByHql(hql.toString(), 0, 0, map, null);
		return list;
	}

	@Override
	public List<UserActionPointConfig> getPointConfigInit(Integer appId,
			Integer pageNo, Integer pageSize) {
		StringBuffer hql = new StringBuffer(
				"select t from UserActionPointConfig t");
		hql.append(" where t.appId=:appId order by actionType asc, createDt desc");
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("appId", GenericConstants.APP_ID_PRE + appId);
		// 查询用户信息
		List<UserActionPointConfig> list = userActionPointConfigDao.findByHql(
				hql.toString(), pageNo, pageSize, map, null);
		return list;
	}

	@Override
	public Integer getPointConfigInitCount(Integer appId) {
		StringBuffer hql = new StringBuffer(
				"select count(*) from UserActionPointConfig t");
		hql.append(" where t.appId=:appId");
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("appId", GenericConstants.APP_ID_PRE + appId);
		List<Long> list = userActionPointConfigDao.findByHqlCount(
				hql.toString(), 0, 0, map, null);
		if (list != null && list.size() == 1) {
			return list.get(0).intValue();
		} else {
			return 0;
		}
	}

	@Override
	public void saveUsePoint(UserActionPointConfig pointConfig, Integer appId,
			Long intUserId) {
		pointConfig.setAppId(GenericConstants.APP_ID_PRE + appId);
		pointConfig.setCreateBy(intUserId);
		pointConfig.setCreateDt(new Date());
		userActionPointConfigDao.save(pointConfig);
	}

	@Override
	public boolean getPointConfigByTypeAndTarget(String actionType,
			Long targetId, Integer appId) {
		StringBuffer hql = new StringBuffer(
				"select count(*) from UserActionPointConfig t");
		hql.append(" where t.appId=:appId");
		hql.append(" and t.actionType=:actionType");
		if (targetId != null) {
			hql.append(" and t.targetId=:targetId");
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("appId", GenericConstants.APP_ID_PRE + appId);
		map.put("actionType", actionType);
		if (targetId != null) {
			map.put("targetId", targetId);
		}
		List<Long> list = userActionPointConfigDao.findByHqlCount(
				hql.toString(), 0, 0, map, null);
		if (list != null && list.size() == 1) {
			if (list.get(0) == 0l) {
				return false;
			}
			return true;
		} else {
			return false;
		}
	}

	@Override
	public void removePointConfigById(Long id) {
		userActionPointConfigDao.delete(id);
	}

	@Override
	public UserActionPointConfig getPointConfig(Long id) {
		return userActionPointConfigDao.get(id);
	}

	@Override
	public void updatePointConfig(UserActionPointConfig pointConfig,
			Long intUserId) {
		UserActionPointConfig record = userActionPointConfigDao.get(pointConfig
				.getId());
		record.setActionType(pointConfig.getActionType());
		record.setTargetId(pointConfig.getTargetId());
		record.setAddPoints(pointConfig.getAddPoints());
		record.setMaxIn(pointConfig.getMaxIn());
		record.setUpdateDt(new Date());
		record.setUpdateBy(intUserId);
		userActionPointConfigDao.update(record);
	}

	@Override
	public String[] getUserNamesByIds(String[] userIds) {
		return usersDao.getUserNamesByIds(userIds);
	}

	@Override
	public Boolean checkUserName(String userName, Integer appId) {
		Users users = usersDao.getUserByUserName(userName,
				GenericConstants.APP_ID_PRE + appId);
		if (users != null) {
			return true;
		} else {
			return false;
		}
	}

	@Override
	public void saveUsers(Users users) {
		usersDao.save(users);
	}
}
